﻿using Abp.Configuration.Startup;
using Abp.Runtime.Session;
using App.EntityFramework;
using System.Collections.Generic;
using System.Linq;
using System;
using EntityFramework.DynamicFilters;

namespace App
{
    public class CommonAppService : AppServiceBase,ICommonAppService
    {
        private readonly IMultiTenancyConfig _multiTenancyConfig;
        public CommonAppService(IMultiTenancyConfig multiTenancyConfig) {
            _multiTenancyConfig = multiTenancyConfig;
        }

        public List<T> GetPageRecords<T>(string where, int page, int rows, string sort, string order, out int total, string filterRules = "", string[] includes = null)
        {
            using (var db = new WebPlusDbContext())
            {
                var query = db.QueryByESql<T>(where, page, rows, sort, order, out total,
                    filterRules, includes, GetTenantFilter());

                return query.ToList();
            }
        }

        public List<T> GetRecords<T>(string where, string sort = "CreationTime", string order = "DESC", string filterRules = "", string[] includes = null)
        {
            using (var db = new WebPlusDbContext())
            {
                return db.QueryByESql<T>(where, "c." + sort + " " + order, filterRules, includes, GetTenantFilter()).ToList();
            }
        }

        private string GetTenantFilter() {
            return "c.TenantId="+ (AbpSession.TenantId.HasValue ? AbpSession.GetTenantId().ToString() : "null");
        }
    }
}
